<template>
  <!-- 年龄、运营商、平台、  不限(UNKNOWN)   字段传值要删除 -->
  <!-- 手机价格为空则不限 -->
  <div>
    <a-spin tip="Loading..." :spinning="formLoading">
      <a-form-model
        :model="confData"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        ref="ruleForms"
      >
        <!-- 名称 -->
        <a-form-model-item label="定向包名称" prop="name">
          <a-input v-model="confData.name" />
        </a-form-model-item>
        <!-- 描述 -->
        <a-form-model-item label="定向包描述" prop="description">
          <a-textarea v-model="confData.description" :auto-size="{ minRows: 2, maxRows: 6 }"/>
        </a-form-model-item>
        <!-- 类型 -->
        <a-form-model-item label="定向包类型" prop="landing_type">
          <a-select v-model="confData.landing_type">
              <a-select-option
                v-for="(item,index) in this.$global.fixPackageType"
                :key="index"
                :value="item.value"
              >
              {{ item.label }}
              </a-select-option>
            </a-select>
        </a-form-model-item>
        <!-- 地域 -->
        <a-form-model-item label="地域">
          <a-radio-group
            v-model="audienceTemplete.district"
            button-style="solid"
          >
            <a-radio-button :value="city.value" v-for="city,index in district " :key="index">
              {{ city.label }}
            </a-radio-button>
          </a-radio-group>

        </a-form-model-item>
        <!-- 省市 -->
        <a-form-model-item v-if="audienceTemplete.district === 'CITY'" label=" ">
          <city
            v-model="audienceTemplete.city"
            :citys.sync="citys"
          ></city>
        </a-form-model-item>
        <!-- 广告投放范围 -->
        <a-form-model-item label="广告投放范围">
          <a-radio-group v-model="audienceTemplete.delivery_range" button-style="solid" >
            <a-radio-button
              v-for="(item,index) in this.$global.deliveryRange"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <!-- 广告投放范围 -->
        <a-form-model-item label="性别">
          <a-radio-group v-model="audienceTemplete.gender" button-style="solid" >
            <a-radio-button
              v-for="(item,index) in this.$global.audienceGender"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <!-- 年龄 -->
        <a-form-model-item class="formTemp" label="年龄">
          <a-checkbox-group
            v-model="audienceTemplete.age"
            button-style="solid"
          >
            <a-checkbox
              v-for="(item,index) in this.$global.audienceAgeBetween"
              :key="index"
              :value="item.value"
              :disabled="audienceTemplete.age.length === 1 && audienceTemplete.age[0] === item.value "
              @change="v=>checkboxChange(v,item.value,'age')"
            >
              {{ item.label }}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
        <!-- 运营商 -->
        <a-form-model-item class="formTemp" label="运营商">
          <a-checkbox-group
            v-model="audienceTemplete.carrier"
            button-style="solid"
          >
            <a-checkbox
              v-for="(item,index) in this.$global.audienceCarrier"
              :key="index"
              :value="item.value"
              :disabled="audienceTemplete.carrier.length === 1 && audienceTemplete.carrier[0] === item.value "
              @change="v=>checkboxChange(v,item.value,'carrier')"
            >
              {{ item.label }}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
        <!-- 网络类型 -->
        <a-form-model-item class="formTemp" label="网络类型">
          <a-checkbox-group
            v-model="audienceTemplete.ac"
            button-style="solid"
          >
            <a-checkbox
              v-for="(item,index) in this.$global.audienceAc"
              :key="index"
              :value="item.value"
              :disabled="audienceTemplete.ac.length === 1 && audienceTemplete.ac[0] === item.value "
              @change="v=>checkboxChange(v,item.value,'ac')"
            >
              {{ item.label }}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
        <!-- 平台 -->
        <a-form-model-item class="formTemp" label="平台">
          <a-checkbox-group
            v-model="audienceTemplete.platform"
            button-style="solid"
          >
            <a-checkbox
              v-for="(item,index) in this.$global.audiencePlatform"
              :key="index"
              :value="item.value"
              :disabled="audienceTemplete.platform.length === 1 && audienceTemplete.platform[0] === item.value "
              @change="v=>checkboxChange(v,item.value,'platform')"
            >
              {{ item.label }}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
        <!-- 文章分类判断 -->
        <a-form-model-item class="formTemp" label="文章分类">
          <a-radio-group
            v-model="is_article_category"
            button-style="solid"
          >
            <a-radio-button :value="city.value" v-for="city,index in article_category " :key="index">
              {{ city.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <!-- 文章分类 -->
        <a-form-model-item v-if="is_article_category" class="formTemp" label=" ">
          <transfer
            v-model="audienceTemplete.article_category"
            :categoryType="'article_category'"
            :articleCategoryValue="this.$global.articleCategory"
          ></transfer>
        </a-form-model-item>
        <!-- 行为兴趣类型 -->
        <a-form-model-item class="formTemp" label="行为兴趣">
          <a-radio-group
            v-model="audienceTemplete.interest_action_mode"
            button-style="solid"
          >
            <a-radio-button
              v-for="(item,index) in this.$global.actionInterest"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <!-- 自定义行为兴趣 -->
        <a-form-model-item v-if="audienceTemplete.interest_action_mode === 'CUSTOM'" class="formTemp" label="行为兴趣">
          <interest
            v-model="audienceTemplete.action_categories"
          ></interest>
          <span v-if="audienceTemplete.interestCategory" v-decorator="['interest_categories']"></span>
        </a-form-model-item>
        <!-- 手机品牌判断 -->
        <a-form-model-item class="formTemp" label="手机品牌">
          <a-radio-group v-model="is_device_brand" button-style="solid" >
            <a-radio-button :value="item.value" v-for="item,index in device_brand " :key="index">
              {{ item.label }}
            </a-radio-button>
          </a-radio-group>

          <div v-if="is_device_brand">
            <a-checkbox-group
              v-model="audienceTemplete.device_brand"
              button-style="solid"
            >
              <a-checkbox
                v-for="(item,index) in this.$global.deviceBrand"
                :key="index"
                :disabled="audienceTemplete.device_brand.length <= 1 && audienceTemplete.device_brand[0] === item.value "
                :value="item.value"
              >
                {{ item.label }}
              </a-checkbox>
            </a-checkbox-group>
          </div>
        </a-form-model-item>
        <!-- 手机价格 -->
        <a-form-model-item  class="formTemp" label="手机价格">
          <a-radio-group v-model="is_prices" button-style="solid" >
            <a-radio-button :value="item.value" v-for="item,index in prices " :key="index">
              {{ item.label }}
            </a-radio-button>
          </a-radio-group>

          <div v-if="is_prices">
            <launch-price v-model="audienceTemplete.launch_price" ></launch-price>
          </div>
        </a-form-model-item>
        <!-- 是否智能放量 -->
        <a-form-model-item  class="formTemp" label="智能放量">
          <a-radio-group v-model="audienceTemplete.auto_extend_enabled" button-style="solid" >
            <a-radio-button :value="item.value" v-for="item,index in auto_extend_enabled " :key="index">
              {{ item.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <!-- 智能放量定向 -->
        <a-form-model-item v-if="audienceTemplete.auto_extend_enabled === 1" class="formTemp" label="智能放量定向">
          <a-checkbox-group
            v-model="audienceTemplete.auto_extend_targets"
            button-style="solid"
          >
            <a-checkbox
              v-for="(item,index) in this.$global.autoExtendTargets"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
      </a-form-model>
    </a-spin>

    <div  class="packageActive">
      <a-spin tip="Loading..." :spinning="estimateLoading">
        <audience-number :citys="citys" :estimateAudience="estimateAudience" :estimateData="estimateData" />
      </a-spin>
    </div>
  </div>
</template>

<script>
import { getAccountListGet } from "@/api/adv/account";
import { getEstimateAudience } from "@/api/headlinesApi/index.js";  // 受众预估

const const_district = [
  { value:'NONE',label:'不限' },
  { value:'CITY',label:'省市' },
]
const const_article_category = [
  { value:false,label:'不限' },
  { value:true,label:'文章分类' },
]
const const_device_brand = [
  { value:false,label:'不限' },
  { value:true,label:'按手机品牌' },
]
const const_prices = [
  { value:false,label:'不限' },
  { value:true,label:'按手机价格' },
]
const const_auto_extend_enabled = [
  { value:0,label:'关闭' },
  { value:1,label:'开启' },
]

export default {
  props:{
    formData:{
      type:Object
    },
    basisData:{
      type:Object
    }
  },
  components:{
    'city':()=>import('./components/city'),
    'transfer':()=>import('./components/transfer'),
    'interest':()=>import('./components/interest'),
    'launchPrice':()=>import('./components/launchPrice'),
    'audienceNumber':()=>import('./components/audienceNumber'),  // 预估数
  },
  data() {
    return {
      accountId:'',
      estimateLoading:false,  // 受众加载
      formLoading:false,  // form加载
      estimateData:{},  // 受众预估人数
      rules: {
        name: [ { required: true, message: '请输入定向包名称', trigger:'change' }],
        description: [ { required: true, message: '请输入定向包描述', trigger:'change' }],
        landing_type: [ { required: true, message: '请选择定向包类型', trigger:'change' }],
      },
      // 映射字段
      district:const_district,
      article_category:const_article_category,
      device_brand:const_device_brand,
      prices:const_prices,
      auto_extend_enabled:const_auto_extend_enabled,
      // 判断字段
      is_article_category:false, // 用于判断是否文章分类  （只做判断）
      is_interest_action_mode:false, //  用于判断是否行为兴趣  （只做判断）
      is_device_brand:false,
      is_prices:false,

      estimateAudience:{},// 受众预估数 映射数据
      citys:[], //城市 映射数据
      // 定向模板数据
      confData:{
        name: '',   // 
        description:'',
        landing_type:'',
      },
      audienceTemplete:{
        district:'NONE', // 地域类型
        city:[], //地域
        delivery_range: "DEFAULT", //广告投放范围
        gender: "NONE", //性别
        age:['UNKNOWN'], //年龄
        carrier:['UNKNOWN'], //运营商
        ac:['unknown'], //网络类型
        platform:['UNKNOWN'], // 受众平台
        article_category:[], //文章分类
        interest_action_mode:'UNLIMITED',  // 行为兴趣类型
        device_brand:['HONOR'], //手机品牌
        launch_price:[], //手机价格
        auto_extend_enabled:0, // 是否智能放量
        auto_extend_targets:[], // 智能放量定向
      },
    };
  },
  // watch 监听多个值
  computed: {
    manyData () {
      const { is_article_category, is_interest_action_mode,is_device_brand,is_prices } = this
      return { is_article_category, is_interest_action_mode, is_device_brand, is_prices }
    }
  },
  watch:{
    // 文章分类、行为兴趣、手机品牌、手机价格 为不限时
    manyData:function (newData) {   
      if( !newData.is_article_category ) this.audienceTemplete.article_category = []
      // if( !newData.is_interest_action_mode ) this.audienceTemplete.article_category = []
      if( !newData.is_device_brand ) this.audienceTemplete.device_brand = ['HONOR']
      if( !newData.is_prices ) this.audienceTemplete.launch_price = []
    },
    audienceTemplete:{
      deep:true,
      handler(params){
        this.$nextTick(()=>{
          let arr = this.$deepCopy(params)

          if( arr.city.length === 0 ) delete arr.city  // 省市
          if( arr.gender === 'NONE' ) delete arr.gender  // 性别
          if( arr.age[0] === 'UNKNOWN' ) delete arr.age // 年龄
          if( arr.carrier[0] === 'UNKNOWN' ) delete arr.carrier // 运营商
          if( arr.ac[0] === 'unknown' ) delete arr.ac // 网络类型
          if( arr.platform[0] === 'UNKNOWN' ) delete arr.platform // 受众平台
          if( !this.is_article_category || arr.article_category.length === 0 ) delete arr.article_category // 文章分类
          // 选择了手机品牌定向, 平台必须选择Android
          if( !this.is_device_brand || arr.device_brand.length === 0 ) delete arr.device_brand // 手机品牌
          if( !this.is_prices || arr.launch_price.length === 0 ) delete arr.launch_price // 手机价格
          if( arr.auto_extend_enabled === 0 ) delete arr.auto_extend_targets // 是否智能放量
          if( arr.auto_extend_enabled === 0 || arr.auto_extend_targets.length === 0 ) delete arr.auto_extend_targets // 智能放量定向
          this.estimateAudience = arr
          
          this.getEstimate(this.accountId,arr)
        })
      }
    }
  },
  created(){
    this.getAccount()
  },
  methods: {
    // 获取用户的第一个账户id
    async getAccount(){
      const res = await getAccountListGet( { status:'ENABLE' } )
      console.info(res,'res2')
      if(res.code === 'SUCCESS'){
        this.accountId = res.data[0].account_id
        if( Object.keys(this.formData).length !== 0  ){
          this.confData = Object.assign( this.confData,this.basisData )
          this.audienceTemplete = Object.assign( this.audienceTemplete,this.formData )
        }
        else this.getEstimate(this.accountId)
      } 
      else await this.getAccount()
    },
    // 获取受众预估数
    async getEstimate(account_id,param){
      if( account_id ){
        this.estimateLoading = true
        let params = { advertiser_id:account_id }
        if(param){
          for (const key in param) {
            if(!!param[key]){
              params[key] = param[key]
            }
          }
        }
        const res = await getEstimateAudience(account_id,params)
        if( res.code === 'SUCCESS' ) this.estimateData = res.data
        this.estimateLoading = false
      }
    },
    // 多选判断
    checkboxChange(check,item,type){
      // let index = this.audienceTemplete[type]
      // if( type === 'age' ){  // 年龄
      //   if( check.target.value === "UNKNOWN" ) this.audienceTemplete.age.splice(0),this.audienceTemplete.age = ['UNKNOWN']
      //   else if( this.audienceTemplete.age.indexOf( 'UNKNOWN' ) !== -1 ) this.audienceTemplete.age.splice(this.audienceTemplete.age.indexOf( 'UNKNOWN' ),1)
      // }
      // if( type === 'carrier' ){  // 运营商
      //   if( check.target.value === "UNKNOWN" ) this.audienceTemplete.carrier.splice(0),this.audienceTemplete.carrier = ['UNKNOWN']
      //   else if( this.audienceTemplete.carrier.indexOf( 'UNKNOWN' ) !== -1 ) this.audienceTemplete.carrier.splice(this.audienceTemplete.carrier.indexOf( 'UNKNOWN' ),1)
      // }
      if( type === 'ac' ){  // 网络类型
        if( check.target.value === "unknown" ) this.audienceTemplete.ac.splice(0),this.audienceTemplete.ac = ['UNKNOWN']
        else if( this.audienceTemplete.ac.indexOf( 'unknown' ) !== -1 ) this.audienceTemplete.ac.splice(this.audienceTemplete.ac.indexOf( 'UNKNOWN' ),1)
      }else {
        if( check.target.value === "UNKNOWN" ) this.audienceTemplete[type].splice(0),this.audienceTemplete[type] = ['UNKNOWN']
        else if( this.audienceTemplete[type].indexOf( 'UNKNOWN' ) !== -1 ) this.audienceTemplete[type].splice(this.audienceTemplete[type].indexOf( 'UNKNOWN' ),1)
      }
      // if( type === 'platform' ){  // 平台
      //   if( check.target.value === "UNKNOWN" ) this.audienceTemplete.platform.splice(0),this.audienceTemplete.platform = ['UNKNOWN']
      //   else if( this.audienceTemplete.platform.indexOf( 'UNKNOWN' ) !== -1 ) this.audienceTemplete.platform.splice(this.audienceTemplete.platform.indexOf( 'UNKNOWN' ),1)
      // }
    },
    // 提交
    handleSubmit() {
      this.$refs['ruleForms'].validate(valid => {
        if (valid) {
          this.formLoading = true
          let audienceTemplete_copy = this.$deepCopy(this.audienceTemplete)
          if( audienceTemplete_copy.district === 'NONE' ) delete audienceTemplete_copy.city  // 地域为不限 删除省市城市
          if( audienceTemplete_copy.age[0] === 'UNKNOWN' ) delete audienceTemplete_copy.age // 年龄
          if( audienceTemplete_copy.carrier[0] === 'UNKNOWN' ) delete audienceTemplete_copy.carrier // 运营商
          if( audienceTemplete_copy.platform[0] === 'UNKNOWN' ) delete audienceTemplete_copy.platform // 受众平台
          if( audienceTemplete_copy.ac[0] === 'unknown' ) delete audienceTemplete_copy.ac // 网络类型

          if( !this.is_prices ) delete audienceTemplete_copy.launch_price // 手机价格
          if( !this.is_article_category ) delete audienceTemplete_copy.article_category // 文章分类
          // 选择了手机品牌定向, 平台必须选择Android
          if( !this.is_device_brand ) delete audienceTemplete_copy.device_brand // 手机品牌
          if( audienceTemplete_copy.auto_extend_enabled === 0 ) delete audienceTemplete_copy.auto_extend_targets // 是否智能放量  删除智能放量定向

          let submit = Object.assign( audienceTemplete_copy,this.confData )
          this.$emit('subimtData',submit,this.estimateData)
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
// 受众人群
  .packageActive{
    width: 200px;
    padding: 10px;
    position: absolute;
    top: 40%;
    right: 20px;
    border-radius: 5px;
    border: 2px solid #C9C9CA;
  }
  // 多选checkbox
  .ant-checkbox-wrapper{   // 未选中样式
    padding: 5px;
    border-radius: 5px;
    border: 1px solid #D9D9D9;
  }
  .ant-checkbox-wrapper-checked{   // 选中样式
    color: white;
    background-color: #31CDC8;
    border: 1px solid #31CDC8;
  }
  .formTemp ::v-deep .ant-checkbox{
    display: none;
  }
  
  // 相邻兄弟选择器   +   可选择紧接在另一元素后的元素，且二者有相同父元素
  ::v-deep .ant-checkbox-disabled + span{
    color: white;
  }

</style>